﻿using System;
using System.Linq;
using System.Reflection;

namespace Asd.MP.Utility
{
    /// <summary>
    /// 简单工厂类
    /// </summary>
    internal class Factory
    {
        private string _assembly, _connectionString;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="assemblyName">程序集名称</param>
        /// <param name="connectionString">数据访问连接字符串</param>
        public Factory(string assemblyName, string connectionString)
        {
            this._assembly = assemblyName;
            this._connectionString = connectionString;
        }
        /// <summary>
        /// 根据类名称创建类实例
        /// </summary>
        /// <typeparam name="T">类的类型（接口，例：IClassModule）</typeparam>
        /// <param name="className">类名（例：ClassModule）</param>
        /// <returns>类的实例</returns>
        public T CreateClassByName<T>(string className)
        {
            if (string.IsNullOrEmpty(className))
            {
                throw new Exception("必须提供类的名称，例：ClassModule");
            }
            Assembly assembly = Assembly.Load(this._assembly);
            Type classPath = assembly.GetTypes().First<Type>(m =>
            {
                return m.Name.ToLower() == className.ToLower();
            });
            if (classPath == null)
            {
                throw new Exception("提供的类的名称在指定程序集不存在");
            }
            return (T)assembly.CreateInstance(
                classPath.FullName, false, BindingFlags.Default,
                null, /*new object[] { this._connectionString }*/null, null, null);
        }

    }


}
